package org.adorsys.aderp.orga.xchange;

import java.lang.reflect.InvocationTargetException;

import javax.annotation.Resource;

import org.adorsys.aderp.jpa.api.xchange.XchangeRecordService;
import org.adorsys.aderp.jpa.api.xchange.DataQuery;
import org.adorsys.aderp.jpa.api.xchange.DataRequest;
import org.adorsys.aderp.jpa.api.xchange.DataResponse;
import org.adorsys.aderp.jpa.api.xchange.DataView;
import org.adorsys.aderp.jpa.api.xchange.ObjectMapper;
import org.adorsys.aderp.orga.domain.OrgaPerson;
import org.adorsys.aderp.orga.service.OrgaPersonService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class OrgaPersonXChangeRecordService implements XchangeRecordService {

	@Resource
	private OrgaPersonService orgaPersonService;
	
	@Override
	public DataResponse loadEntity(DataRequest dataRequest) {
		if(OrgaPerson.class.getName().equals(dataRequest.getEntityName())){
			try {
				return loadOrgaPerson(dataRequest);
			} catch (Exception e) {
				DataResponse dataResponse = new DataResponse();
				dataResponse.setResultCode(DataResponse.RESULT_CODE_ERROR);
				return dataResponse;
			}
		}
	
		return new DataResponse();
	}

	@Override
	public Page<DataResponse> searchEntities(DataQuery dataQuery,
			Pageable pageable) {
		throw new UnsupportedOperationException();
	}

	private DataResponse loadOrgaPerson(DataRequest dataRequest) 
			throws IllegalAccessException, 
			InvocationTargetException, NoSuchMethodException 
	{
		String personNumber = dataRequest.getEntityKey();
		OrgaPerson orgaPerson = orgaPersonService.findByPersonNumber(personNumber);
		DataView dataView = dataRequest.getDataView();
		DataResponse dataResponse = new DataResponse();
		dataResponse.setEntityKey(personNumber);
		dataResponse.setEntityName(dataRequest.getEntityName());
		ObjectMapper objectMapper = new ObjectMapper(dataView);
		dataResponse.getEntityData().putAll(objectMapper.toMap(orgaPerson));
		return dataResponse;
	}

}
